package com.example.demo.controller;



import com.example.Demo_DelayQueue.DelayTask;
import com.example.demo.pojo.DelayTask2;
import com.example.demo.queue.HelloDelayQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.DelayQueue;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/DelayQueueTest")
public class DelayQueueController {
    //创建bean的时候给这个属性一个初始值
    DelayQueue<DelayTask> delayTasks=new DelayQueue<>();

    @RequestMapping("/add")
    public String delayQueueTest() {
        System.out.println("test1here");
        delayTasks.add(new DelayTask("测试4", 3L,TimeUnit.SECONDS));
        return "success";
    }

    @RequestMapping("/take")
    public String delayQueueTest2() throws InterruptedException {
        System.out.println("Test2here");

        //这个是IDEA建议的在使用多线程代码模块的时候,一个桥接局部变量的方式
        final DelayTask[] take = new DelayTask[1];
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while ((take[0] = delayTasks.take()) != null) {
                        System.out.println(".............");
                        take[0].sayHello();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return "success";
    }

}

